#!/usr/bin/python
import cgi
import string
import os,sys
import traceback
from PageMaker import HTMLPage


def ckLogin(user):
	ckinfo = 0
	f = open("user_info.txt","r")
	for line in f:
		tempInfo = line.strip()
		tempLine = tempInfo.split("|")
		if tempLine[0] == user:
			ckinfo = -1
	f.close()
	return ckinfo

def maxExt():
	m_ext = 0
	f = open("user_info.txt","r")
	for line in f:
		tempInfo = line.strip()
		tempLine = tempInfo.split("|")
		if m_ext < int(tempLine[3]):
			m_ext = int(tempLine[3])
	return m_ext


print "Content-type: text/html"
print

myPage = HTMLPage()



fs = cgi.FieldStorage()
user_name = fs.getvalue("log_id")
pswd = fs.getvalue("pswd")
pswd1 = fs.getvalue("pswd2")
email = fs.getvalue("email")
ext = maxExt()


user_name_fnd = 1
ext_fnd = 1


try:
	if ckLogin(user_name) == 0:
		#Unique id, ok to add
		if pswd == pswd1 and user_name != None:
			ext = ext + 1
			f = open("user_info.txt","a")
			f.write(str(user_name)+ "|" + str(pswd) + "|" + str(email) + "|" + str(ext) + "\n")
			f.close()
			myPage.addTitle("Welcome to VITSystem")
			myPage.printMainPage(user_name)
#			myPage.addElement("<a href='add_calendar.cgi' style='color: blue;'>Add/Remove Google Calendar</a>","","","")
#			myPage.addElement("<br><a href='add_zipcodes.cgi' style='color: blue;'>Add/Remove Zipcodes for weather</a>","","","")
#			myPage.addElement("","hidden","lid",user_name)
			

		else:
			myPage.addForm("new_login.cgi","post","")
			myPage.addTitle("Sorry, passwords do not match.  Please try again")
	else:
		myPage.addForm("new_login.html","post","")
		myPage.addElement("Sorry, that login ID has been take.  Please try again<br>","","","")
		myPage.addElement("","submit","goback","Click here to continue")

#	myPage.addElement("","submit","Continue","Continue")
#	myPage.printForm()

except:
	print "fs.getvalue('log_id')",fs.getvalue("log_id")
	print "Unable to open file"
	etype = sys.exc_info()[0]
	evalue = sys.exc_info()[1]
	etb = traceback.extract_tb(sys.exc_info()[2])

	print "etype=",str(etype)
	print ""
	print "evalue=",str(evalue)
	print ""
	print "traceback",str(etb)

